import dotenv
from fastapi import APIRouter, Query
from fastapi.responses import JSONResponse
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_ollama import ChatOllama
from ..settings.settings import Settings
from openai import OpenAI

router = APIRouter()

# -----------------------------
# 本地 Ollama 接口
# -----------------------------
# 定义 Prompt 模板
prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一个资深文学家"),
    ("human", "请简短赏析{name}这首诗，并给出评价")
])

# 初始化 Ollama 模型
llm = ChatOllama(
    model="qwen3:0.6b",
    base_url="http://172.16.21.38:11436"
)

# StrOutputParser
parser = StrOutputParser()


@router.get("/poem_analysis")
async def poem_analysis(name: str = Query(..., description="诗的名称")):
    # 渲染 Prompt
    formatted_prompt = prompt.format_messages(name=name)
    # 调用 Ollama
    response = llm(formatted_prompt)
    # 如果返回的是 AIMessage 对象，先获取 content
    # 如果返回的是列表，则取第一个元素
    if isinstance(response, list):
        message_content = response[0].content
    else:
        message_content = response.content
    # 使用 StrOutputParser 解析纯文本
    result = parser.parse(message_content)
    return JSONResponse(content={"poem_analysis": result})


# -----------------------------
# 云端 DeepSeek 接口
# -----------------------------
# 读取配置
settings = Settings()
DeepSeekUrl = settings.DeepSeekUrl
DeepSeekKey = settings.DeepSeekKey

# 初始化 OpenAI 客户端
client = OpenAI(api_key=DeepSeekKey, base_url=DeepSeekUrl)

@router.get("/poem_analysis_deepseek")
async def poem_analysis_deepseek(name: str = Query(..., description="诗的名称")):
    """使用云端 DeepSeek 分析诗歌"""
    # 使用同样的 ChatPromptTemplate 渲染 Prompt
    formatted_prompt = prompt.format_messages(name=name)
    # 将渲染后的内容提取为字符串
    user_content = " ".join([m.content for m in formatted_prompt if m.type == "human"])
    # 调用 DeepSeek（OpenAI API）
    response = client.chat.completions.create(
        model="deepseek-chat",  # 替换为云端支持的模型
        messages=[{"role": "user", "content": user_content}],
        temperature=0.7
    )
    # 提取文本内容
    text_output = response.choices[0].message.content
    # 使用 StrOutputParser 解析（统一接口）
    result = parser.parse(text_output)
    return JSONResponse(content={"poem_analysis_deepseek": result})
